package com.mrlv.common.http;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Mrlv
 * @date 2021年12月19日 11:56
 */
@Slf4j
public class HttpParamUtil {

    /**
     * 获得url中参数
     * @param url
     * @return
     */
    public static Map<String, Object> getParameter(String url) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            final String charset = "UTF-8";
            url = URLDecoder.decode(url, charset);
            if (url.indexOf('?') != -1) {
                final String contents = url.substring(url.indexOf('?') + 1);
                String[] keyValues = contents.split("&");
                for (int i = 0; i < keyValues.length; i++) {
                    String key = keyValues[i].substring(0, keyValues[i].indexOf("="));
                    String value = keyValues[i].substring(keyValues[i].indexOf("=") + 1);
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            //TODO 处理异常;
        }
        return map;
    }

    /**
     * 获取request中参数
     *
     * @param request 页面请求
     */
    public static Map<String, Object> getRequestParameters(HttpServletRequest request) {

        String urlParameter = request.getQueryString();// 网址中的参数
        if (StrUtil.isNotBlank(urlParameter)) {
            try {
                urlParameter = URLDecoder.decode(urlParameter, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                //TODO 处理异常;
            }
        } else {
            urlParameter = "";
        }
        //请求参数
        String parameters = urlParameter;


        Map<String, Object> map = new HashMap<>();
        String[] arr = parameters.split("&");
        for (int i = 0; i < arr.length; i++) {
            String key = arr[i].substring(0, arr[i].indexOf("="));
            String value = arr[i].substring(arr[i].indexOf("=") + 1);
            map.put(key, value);
        }
        return map;
    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        String url = "www.xxxx.com?id=100001&name=zhangsan&age=25";
        Map<String, Object> map = getParameter(url);
        System.out.println(map);
    }
}
